<template>
	<view class="userInfoEdit">
		<view class="userInfoEdit_haber" :style="{ paddingTop: (top+30) + 'px' }">
			<tui-navigation-bar maxOpacity="0" :titleSize="18" :titleLineHeight="18" :titlefontWeight="800"
				@init="initNavigation" :title="titlte" backgroundColor="#fff" color="#000">
				<view class="tui-header-icon" :style="{ marginTop: top + 'px' }">
					<tui-icon name="arrowleft" color="#333" @click="back"></tui-icon>
				</view>
			</tui-navigation-bar>
			<view class="userInfoEditTop"> </view>
		</view>
		<tui-landscape :show="landscapeShow" :closeIcon="false" :maskClosable="false" iconLeft="50rpx" iconRight="50rpx">
		</tui-landscape>
		<view class="userInfoEdit_Content">
			<view class="img_header">
				<view class="img_opt_header">
					<image class="optImg" :src="ossUrl + (tutorDetails.masterImg||'')" alt="" />
				</view>
				<image @tap="uploadImg" class="icon_camera" src="/static/tutor/message/icon_photo@2x.png" alt="" />
			</view>
			<view class="form_my">
				<view class="item_info">
					<view class="label_info">昵称</view>
					<view class="comp_info">
						<tui-input inputBorder radius="16" padding="22rpx 40rpx" :color="'rgba(102, 102, 102, 1)'" size="28"
							:borderColor="'rgba(243, 230, 211, 1)'" isFillet :backgroundColor="'#FFFEF8'" placeholder="请输入昵称"
							v-model="tutorDetails.assistantName"></tui-input>
					</view>
				</view>
				<view class="item_info">
					<view class="label_info">个性签名</view>
					<view class="comp_info">
						<tui-input inputBorder radius="16" padding="22rpx 40rpx" :color="'rgba(102, 102, 102, 1)'" size="28"
							:borderColor="'rgba(243, 230, 211, 1)'" isFillet :backgroundColor="'#FFFEF8'"
							v-model="tutorDetails.personalSignature"></tui-input>
					</view>
				</view>
				<view class="item_info">
					<view class="label_info">性别</view>
					<view class="comp_info">
						<view class="comp_infoSelect" @tap="showGenderCategory=true">
							<view class="lt">
								{{ tutorDetails.gender==0?'男':'女'}}
							</view>
							<image class="rt" src="/static/tutor/message/icon_xiala@2x.png"></image>
						</view>
					</view>
				</view>
				<view class="item_info">
					<view class="label_info">手机号</view>
					<view class="comp_info">
						<tui-input inputBorder radius="16" padding="22rpx 40rpx" :color="'rgba(102, 102, 102, 1)'" size="28"
							:borderColor="'rgba(243, 230, 211, 1)'" isFillet :backgroundColor="'#FFFEF8'"
							v-model="tutorDetails.phoneNumber"></tui-input>
					</view>
				</view>
				<view class="item_info">
					<view class="label_info">所属分类</view>
					<view class="comp_info">
						<view class="comp_infoSelect" @tap="showCategory=true">
							<view class="lt">
								{{ categoryName || className}}
							</view>
							<image class="rt" src="/static/tutor/message/icon_xiala@2x.png"></image>
						</view>
					</view>
				</view>
				<view class="item_info">
					<view class="label_info">区域</view>
					<view class="comp_info">
						<view class="comp_infoSelect" @tap="selectAdress">
							<view class="lt">
								{{ tutorDetails.address || tutorDetails.poi&&tutorDetails.poi.district}}
							</view>
							<image class="rt" src="/static/tutor/message/icon_xiala@2x.png"></image>
						</view>
					</view>
				</view>
				<view class="item_info">
					<view class="label_info">时间</view>
					<view class="comp_info">
						<view class="comp_infoSelect" @tap="showTime">
							<view class="lt" v-if="tutorDetails.begintime.hour">
								<text>{{tutorDetails.begintime.hour+':'+tutorDetails.begintime.minute || '开始时间'}}</text>
								—
								<text>{{tutorDetails.endtime.hour+':'+tutorDetails.endtime.minute ||'结束时间'}}</text>
							</view>
							<view class="lt" v-else>
								<text>开始时间</text>
								—
								<text>结束时间</text>
							</view>
							<image class="rt" src="/static/tutor/message/icon_xiala@2x.png"></image>
						</view>
					</view>
				</view>
				<view class="item_info">
					<view class="label_info">等级</view>
					<view class="comp_info">
						<view class="comp_infoSelect">
							<view class="lt">
								{{ tutorDetails.levelName }}
							</view>
						</view>
					</view>
				</view>
				<view class="item_info">
					<view class="label_info">费用</view>
					<view class="comp_info">
						<tui-input disabled inputBorder radius="16" padding="22rpx 40rpx" :color="'#555'" size="28"
							:borderColor="'rgba(243, 230, 211, 1)'" isFillet :backgroundColor="'#f1eded'"
							v-model="tutorDetails.rates">
							<template v-slot:right>
								<view class="rates">
									<text>元/小时</text>
								</view>
							</template>
						</tui-input>
					</view>
				</view>

				<view class="item_info">
					<view class="label_info">图片({{imgs.length}})</view>
					<view class="comp_info">
						<view class="img" v-for="(img,i) in imgs" :key="i">
							<view class="infoBg">
								<image class="infoImg" :src="ossUrl + (img||'')"></image>
							</view>
							<image class="delImg" @tap="delImg(img,i)" src="/static/tutor/message/icon_del@2x (1).png"></image>
						</view>
						<view class="img" v-if="imgs.length<10" @tap="addImg">
							<image class="addImg" src="/static/tutor/message/icon_add1@2x.png"></image>
						</view>
						<!-- <view class="img" v-if="video">
						 	<view class="infoBg">
						 		 <image class="infoImg" :src="ossUrl + (video||'') +'?vframe/jpg/offset/1'"></image>
						 	</view>
						 	 <image class="delImg" @tap="delImg(video,i)" src="/static/tutor/message/icon_del@2x (1).png"></image>
						 </view>
						 <view class="img" v-if="!video" @tap="addVideo">
						 	 <image class="addImg" src="/static/tutor/message/icon_add1@2x.png"></image>
						 </view> -->
					</view>
				</view>
			</view>
		</view>
		<view class="footer">
			<tui-form-button :disabled="saveLoading" :loading="saveLoading" @click="saveShopInfo" margin="24rpx 0 0 0"
				radius="40rpx" :size="32" color="#fff" width="690rpx" height="84rpx" background="#2FD7D3">
				保存
			</tui-form-button>
		</view>
		<tui-datetime :type="4" ref="dateTime" @confirm="changeTime"></tui-datetime>
		<tui-picker :valueField="'id'" :textField="'categoryName'" :show="showCategory" :pickerData="categoryList"
			@hide="showCategory=false" @change="change">
		</tui-picker>
		<tui-picker :show="showGenderCategory" :pickerData="genderList" @hide="showGenderCategory=false"
			@change="hanleChange">
		</tui-picker>
	</view>
</template>

<script>
	import Cache from "@/utils/cache";
	import {
		getCategoryList
	} from "@/http/api/category/category.js"
	import {
		putTutorInfo,
		addTutor,
		getTutorlevelPrice
	} from "@/http/api/tutor/tutor.js"
	export default {
		data() {
			return {
				top: 0, //标题图标距离顶部距离
				marginTp: 0,
				titlte: '编辑',
				ossUrl: getApp().globalData.ossurl,
				landscapeShow: false,
				saveLoading: false, //按钮加载
				categoryId: '', //分类id
				categoryName: '', //分类名称
				categoryList: [], //分类
				levelList: [],
				showCategory: false,
				showGenderCategory: false,
				genderList: [{
					text: "男",
					value: "0"
				}, {
					text: "女",
					value: "1"
				}],
				tutorDetails: {
					masterImg: '', //教练主图
					phoneNumber: '', //手机号
					levelName: '', //等级
					levelId: '', //等级id
					merchantId: '', //所属商家
					gender: '0',
					assistantName: '', //教练名称
					personalSignature: '', //个性签名
					begintime: {
						hour: '',
						minute: ''
					}, //营业开始时间
					endtime: {
						hour: '',
						minute: ''
					}, //营业结束时间
					poi: {
						province: '',
						city: '',
						district: '',
						businessAreaName: '',
					}, //商圈信息
					address: '', //地址
					detailImgs: [], //教练详情图片
					phoneNumber: '', //手机号
					coordinates: {
						lng: '',
						lat: ''
					},

				}, //当前店铺信息
				imgs: [], //图片img
				video: '', //视频
			}
		},
		onUnload() {
			uni.$off('adressInfo')
		},
		onLoad(options) {
			// getTutorlevelPrice().then(res=>{
			// 		if(res.code){
			// 			console.log(res,'等级')
			// 		}
			// 	})
			uni.$on('adressInfo', (e) => {
				this.tutorDetails.address = e.address
				this.tutorDetails.poi = e.poi
				this.tutorDetails.coordinates.lng = e.longitude
				this.tutorDetails.coordinates.lat = e.latitude
			})
			if (options && options.isAdd === "true") {
				this.titlte = '添加'
				this.tutorDetails.merchantId = options.merchantId
				this.tutorDetails.coordinates = {
					lng: Cache.get('longitude'),
					lat: Cache.get('latitude')
				}
			} else {
				let tutorDetails = JSON.parse(options.tutorDetails)
				if (!tutorDetails.address) {
					tutorDetails.address = tutorDetails.poi && tutorDetails.poi.district
				}
				this.tutorDetails = tutorDetails
				this.tutorDetails
				this.tutorDetails.begintime = {
					hour: tutorDetails.begintime ? tutorDetails.begintime.split(':')[0] : '',
					minute: tutorDetails.begintime ? tutorDetails.begintime.split(':')[1] : ''
				}
				if (!tutorDetails.coordinates) {
					this.tutorDetails.coordinates = {
						lng: Cache.get('longitude'),
						lat: Cache.get('latitude')
					}
				}
				if (tutorDetails.detailImgs && tutorDetails.detailImgs.length) {
					if (this.isImage(tutorDetails.detailImgs[tutorDetails.detailImgs.length - 1])) {
						this.imgs = tutorDetails.detailImgs
					} else {
						if (tutorDetails.detailImgs.length === 1) {
							this.video = tutorDetails.detailImgs[0]
						} else {
							this.imgs = tutorDetails.detailImgs.slice(0, -1)
							this.video = tutorDetails.detailImgs[tutorDetails.detailImgs.length - 1]
						}
					}
				}
				if (!tutorDetails.poi) {
					this.tutorDetails.poi = {
						province: '',
						city: '',
						district: '',
						businessAreaName: ''
					}
				}
				this.tutorDetails.endtime = {
					hour: tutorDetails.endtime ? tutorDetails.endtime.split(':')[0] : '',
					minute: tutorDetails.endtime ? tutorDetails.endtime.split(':')[1] : ''
				}
				this.titlte = '编辑'
			}

			this.getCategorys()
		},
		computed: {
			className() {
				if (this.categoryList.length) {
					if (this.tutorDetails.categoryId) {
						let data = this.categoryList.filter(item => item.id === this.tutorDetails.categoryId)
						return data[0].categoryName
					}
				}
			}
		},
		methods: {
			isImage(filename) {
				const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.svg'];
				const fileExtension = filename.slice(filename.lastIndexOf('.'));
				return imageExtensions.includes(fileExtension.toLowerCase());
			},
			//获取分类列表
			getCategorys() {
				getCategoryList().then(res => {
					if (res.code) {
						this.categoryList = res.data
						console.log(res, '分类数据')
					}
				})
			},
			//选择等级
			changeLevel(e) {
				this.tutorDetails.levelId = e.id
				this.tutorDetails.levelName = e.result
				if (!this.categoryId && !this.tutorDetails.categoryId) {
					uni.showToast({
						icon: "none",
						title: "请选择分类！",
					});
					return
				}
				getTutorlevelPrice(e.id, this.categoryId).then(res => {
					if (res.code == 200) {
						this.tutorDetails.rates = res.data && res.data.price || ''
					}
				})
			},
			hanleChange(e) {
				this.tutorDetails.gender = e.value
			},
			//选择分类
			change: function(e) {
				//选择的分类结果
				this.categoryId = e.id
				this.categoryName = e.result
			},
			//调用此方法显示选择器，需等组件初始化完成后调用，避免在onLoad中调用
			showTime: function(e) {
				this.$refs.dateTime && this.$refs.dateTime.show();
			},
			//选择时间
			changeTime: function(e) {
				if (e.hour * 1 < this.tutorDetails.begintime.hour * 1 && this.tutorDetails.endtime.minute * 1 > 0) {
					this.tutorDetails.begintime.hour = e.hour
					this.tutorDetails.begintime.minute = e.minute
					return
				}
				if (this.tutorDetails.begintime.hour) {
					this.tutorDetails.endtime.hour = e.hour
					this.tutorDetails.endtime.minute = e.minute
				} else {
					this.tutorDetails.begintime.hour = e.hour
					this.tutorDetails.begintime.minute = e.minute
				}

			},
			initNavigation(e) {
				this.top = e.top;
				this.marginTp = e.height
			},
			back() {
				uni.navigateBack({
					delta: 1
				});;
			},
			//上传商家主图
			uploadImg() {
				let _this = this;
				uni.showLoading({
					title: '上传中...'
				})
				_this.landscapeShow = true;

				// 使用通用的选择媒体方法
				_this.$utils.chooseMedia({
					count: 1,
					sizeType: ['original', 'compressed'],
					sourceType: ['album', 'camera'],
					mediaType: ['image']
				}, (res, success) => {
					if (success) {
						// 选择成功，上传文件
						_this.$utils.uploadFile(res.tempFilePaths[0], (imgInfo) => {
							if (imgInfo.statusCode == 200) {
								let dataImg = JSON.parse(imgInfo.data);
								_this.$set(_this.tutorDetails, 'masterImg', dataImg.data.fileName);
							} else {
								uni.showToast({
									title: '上传失败',
									icon: 'none',
									duration: 2000
								});
							}
							uni.hideLoading();
							_this.landscapeShow = false;
						});
					} else {
						// 选择失败
						uni.hideLoading();
						_this.landscapeShow = false;
					}
				});
			},
			//获取分类列表
			getCategorys() {
				getCategoryList().then(res => {
					if (res.code) {
						this.categoryList = res.data
						console.log(res, '分类数据')
					}
				})
			},
			//选择店铺位置
			selectAdress() {
				let info = {
					latitude: this.tutorDetails.coordinates && this.tutorDetails.coordinates.lat || '39.54',
					longitude: this.tutorDetails.coordinates && this.tutorDetails.coordinates.lng || '116.25',
					name: this.tutorDetails.address, // 名称
					address: this.tutorDetails.address, // 详细地址
					businessAreaName: this.tutorDetails.poi && this.tutorDetails.poi.businessAreaName || '', // 商圈
					province: this.tutorDetails.poi && this.tutorDetails.poi.province || '', // 省份
					city: this.tutorDetails.poi && this.tutorDetails.poi.city || '', // 城市
					district: this.tutorDetails.poi && this.tutorDetails.poi.district || '', // 区县
				}
				uni.navigateTo({
					url: '/pages/invite/modules/addressSelect/addressSelect?info=' + JSON.stringify(info)
				})
			},
			//上传视频
			addVideo() {
				uni.showLoading({
					title: '上传中...'
				})
				let _this = this;
				_this.landscapeShow = true;

				// 使用通用的选择媒体方法
				_this.$utils.chooseMedia({
					count: 1,
					sourceType: ["camera", "album"],
					maxDuration: 30,
					mediaType: ["video"]
				}, (res, success) => {
					if (success) {
						if (res.tempFiles[0].size / 1024 / 1024 > 50) {
							uni.hideLoading();
							_this.landscapeShow = false;
							return uni.showToast({
								icon: "none",
								title: "拍摄视频过大，请重新拍摄！",
							});
						}

						// 选择成功，上传文件
						_this.$utils.uploadFile(res.tempFilePaths[0], (videoInfo) => {
							if (videoInfo.statusCode == 200) {
								let dataVideo = JSON.parse(videoInfo.data);
								_this.video = dataVideo.data.fileName;
							} else {
								uni.showToast({
									title: '上传失败',
									icon: 'none',
									duration: 2000
								});
							}
							uni.hideLoading();
							_this.landscapeShow = false;
						});
					} else {
						// 选择失败
						uni.hideLoading();
						_this.landscapeShow = false;
					}
				});
			},
			//上传图片
			addImg() {
				uni.showLoading({
					title: '上传中...'
				})
				let _this = this;
				_this.landscapeShow = true;

				// 使用通用的选择媒体方法
				_this.$utils.chooseMedia({
					count: 9,
					sizeType: ['original', 'compressed'],
					sourceType: ['album', 'camera'],
					mediaType: ['image']
				}, (res, success) => {
					if (success) {
						// 选择成功，上传文件
						_this.$utils.uploadFile(res.tempFilePaths[0], (imgInfo) => {
							if (imgInfo.statusCode == 200) {
								let dataImg = JSON.parse(imgInfo.data);
								_this.imgs.push(dataImg.data.fileName);
							} else {
								uni.showToast({
									title: '上传失败',
									icon: 'none',
									duration: 2000
								});
							}
							uni.hideLoading();
							_this.landscapeShow = false;
						});
					} else {
						// 选择失败
						uni.hideLoading();
						_this.landscapeShow = false;
					}
				});
			},
			//删除图片
			delImg(e, index) {
				let that = this
				let isVideo = e.indexOf("mp4") !== -1
				uni.showModal({
					title: "温馨提示",
					content: `确认删除该${isVideo?'视频':'图片'}吗?`,
					confirmText: "确认",
					showCancel: '取消',
					success: (res) => {
						if (res.confirm) {
							// delUploadFile(that.imgs[index].ossId).then(res=>{
							// 	if(res.code==200){
							// 		that.$utils.toast('删除成功')
							// 		that.imgs.splice(index, 1);
							// 	}else{
							// 		that.$utils.toast(res.msg)
							// 	}
							// })
							if (isVideo) {
								that.video = ''
							} else {
								that.imgs.splice(index, 1);
							}
							that.$utils.toast('删除成功')
						}
					},
				});
			},
			//保存教练编辑信息
			saveShopInfo() {
				this.saveLoading = true
				if (!this.tutorDetails.levelId) {
					this.$utils.toast('教练等级不能为空')
					return false
				}
				if (!this.tutorDetails.address) {
					this.$utils.toast('教练所在区域不能为空')
					return false
				}

				// let imgs= this.imgs
				// let detailImgs;
				// if(this.video){
				// 	detailImgs = imgs.concat([this.video])
				// }else{
				// 	detailImgs = imgs
				// }
				let begintime = this.tutorDetails.begintime.hour + ':' + this.tutorDetails.begintime.minute === ':' ? '' : this
					.tutorDetails.begintime.hour + ':' + this.tutorDetails.begintime.minute
				let endtime = this.tutorDetails.endtime.hour + ':' + this.tutorDetails.endtime.minute === ':' ? '' : this
					.tutorDetails.endtime.hour + ':' + this.tutorDetails.endtime.minute
				if (this.titlte === '编辑') {
					putTutorInfo({
							masterImg: this.tutorDetails.masterImg,
							categoryId: this.categoryId || this.tutorDetails.categoryId,
							assistantName: this.tutorDetails.assistantName,
							begintime: begintime,
							endtime: endtime,
							poi: this.tutorDetails.poi,
							phoneNumber: this.tutorDetails && this.tutorDetails.phoneNumber,
							detailImgs: this.imgs,
							levelId: this.tutorDetails.levelId,
							gender: this.tutorDetails.gender,
							rates: this.tutorDetails.rates,
							personalSignature: this.tutorDetails.personalSignature,
							id: this.tutorDetails.id
						}).then(res => {
							if (res.code === 200) {
								this.$utils.toast('编辑成功')
								uni.$emit('tutorRefresh', true)
								uni.navigateBack({
									delta: 1
								});;
								console.log(res, '获取教练编辑成功的数据')
							}
						})
						.finally(() => {
							this.saveLoading = false
						})
				} else {
					addTutor({
							masterImg: this.tutorDetails.masterImg,
							categoryId: this.categoryId,
							phoneNumber: this.tutorDetails && this.tutorDetails.phoneNumber,
							assistantName: this.tutorDetails.assistantName,
							begintime: begintime,
							endtime: endtime,
							gender: this.tutorDetails.gender,
							poi: this.tutorDetails.poi,
							detailImgs: detailImgs,
							rates: this.tutorDetails.rates,
							personalSignature: this.tutorDetails.personalSignature,
							merchantId: this.tutorDetails.merchantId
						}).then(res => {
							if (res.code === 200) {
								this.$utils.toast('添加成功')
								uni.$emit('tutorShopRefresh', true)
								uni.navigateBack({
									delta: 1
								});;
								console.log(res, '获取教练编辑成功的数据')
							}
						})
						.finally(() => {
							setTimeout(() => {
								this.saveLoading = false
							}, 500)
						})
				}

			}
		},
	}
</script>

<style lang="scss" scoped>
	@import './userInfoEdit.scss';
</style>